<?php

namespace app\controller;

use app\BaseController;
use app\model\OrderModel;
use think\facade\Db;
use think\facade\Validate;
use think\Request;
use app\middleware\Check;
use think\validate\ValidateRule;
use think\facade\Cache;

require_once '../sdk/WxpayAPI/lib/WxSend.Api.php';
require_once '../sdk/API-PHP/API_PHP_DEMO.php';

/**
 * Class Order 商户端 订单控制器
 * @package app\controller
 */
class Order extends BaseController
{
    protected $middleware = [Check::class];

    /** 生成订单
     * @param Request $request
     */
    public function new_order(Request $request)
    {
        if (!$request->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $request->post('store_id');//商户ID
        $user_id = $request->post('user_id');//用户ID
        $pay_type = $request->post('pay_type');//支付类型
        $total = $request->post('total');//客户端总价
        $address_id = $request->post('address_id');//地址ID
        $delivery_price = $request->post('delivery_price');//服务费
        $floor_price = $request->post('floor_price');//骑手配送费
        $remark = $request->post('remark');//订单备注
        $lunchbox_price= $request->post('lunchbox_price');//餐盒费
        $is_raised = $request->post('is_raised');//1:送货上楼 2：自提
        if (is_null($is_raised) || is_null($pay_type) || empty($address_id) || empty($store_id) || empty($user_id) || empty($total) || empty($delivery_price)) return jsonFail('缺少参数');
        $error_data = ['store_id' => $store_id, 'user_id' => $user_id, 'pay_type' => $pay_type, 'total' => $total, 'address_id' => $address_id, 'delivery_price' => $delivery_price, 'floor_price' => $floor_price, 'remark' => $remark, 'is_raised' => $is_raised];
        $orderLua = file_get_contents(app()->getAppPath() . 'lua/order.lua');
        $rtn = Cache::store('redis')->handler()->eval($orderLua, [$user_id, $store_id, $address_id], 3);
        if ($rtn == false) return jsonFail('获取缓存失败');
        try {
            $cartInfo = oddEven($rtn[0]);// 0 购物车
            $userInfo = oddEven($rtn[1]); // 1 用户信息
            $userAddressInfo = json_decode($rtn[2], true); // 用户地址信息
            $userAddressInfo = array_pop($userAddressInfo);
            $schoolInfo = oddEven($rtn[3]); // 学校信息
            $storeInfo = oddEven($rtn[4]); // 商户信息
            $goodsIds = [];
            //判断商品费用
            $fuwu = 0;
            $delivery = 0;
            if ($schoolInfo['allow_order'] != 1) return jsonFail('下单时间段11:00–13:00，17:00-19:00！');
//            $school = Cache::store('redis')->handler()->hGet('dxsd-school-' . 1,'delivery');
            if (!array_key_exists('delivery', $schoolInfo)) return jsonFail('暂未获得配送设置');
            $one = explode(',', $schoolInfo['delivery']);
            foreach ($one as $key => $value) {
                $value = explode('-', $value);
                if ($key == 0 && $total < $value[0]) return jsonFail('订单' . $value[0] . '起送');
                if ($key == 0 && $total >= $value[0] && $total <= $value[1]) {//第一次
                    $fuwu = $value[2];//服务费
                    $delivery = $value[3];//配送费
                    break;
                }
                if ($total > $value[0] && $total <= $value[1]) {
                    $fuwu = $value[2];//服务费
                    $delivery = $value[3];//配送费
                    break;
                }
            }
//            if ($fuwu == 0) return jsonFail('服务费系统金额出错');
            if ($is_raised == 1 && $delivery != $floor_price) return jsonFail('配送费系统金额出错');
            if ($fuwu != $delivery_price) return jsonFail('配送金额不相符', [$fuwu, $delivery]);
            foreach ($cartInfo as $key => $value) {
                $cart_data[] = json_decode($value, true);
                $goodsIds[] = json_decode($value, true)['goods_id'];
            }
            $orderGoodsLua = file_get_contents(app()->getAppPath() . 'lua/order_goods.lua');
            $goodsInfo = Cache::store('redis')->handler()->eval($orderGoodsLua, $goodsIds, count($goodsIds));
            if ($goodsInfo == false) return jsonFail('商品获取信息失败，加入购物车的商品已下架，请清空购物车重新下单哦~');
            foreach ($goodsInfo as &$v) {
                $v = oddEven($v);
            }
            $operate_price_tmp = 0;
            $store_price_tmp = 0;
            $goodsInfoTmp = array_column($goodsInfo,null, 'id');
            if (!$goodsInfo) return jsonFail('系统数据错误，下单失败');
            foreach ($cartInfo as $key => $value) {
                $cart = json_decode($value, true);
                $goods_id = $cart['goods_id'];
                if (!isset($goodsInfoTmp[$goods_id]['lunchbox_type']) || !isset($goodsInfoTmp[$goods_id]['lunchbox_type'])) {
                    return jsonFail('系统参数未设置，下单失败');
                }
                if ($goodsInfoTmp[$goods_id]['lunchbox_type'] == 1) {
                    // 运营商收取餐盒费
                    $operate_price_tmp += $goodsInfoTmp[$goods_id]['lunchbox_fee'] * $cart['num'];
                } else {
                    // 商家收取餐盒费
                    $store_price_tmp += $goodsInfoTmp[$goods_id]['lunchbox_fee'] * $cart['num'];
                }
            }

            foreach ($cart_data as $key => $value) {
                $cart_data[$key]['name'] = $goodsInfo[$key]['name'];
                $cart_data[$key]['price'] = $goodsInfo[$key]['price'];
                $cart_data[$key]['stock'] = $goodsInfo[$key]['stock'];
            }

            $total_back = 0;
            foreach ($cart_data as $key => $value) {
                if ($value['num'] <= $value['stock']) {
                    $total_back += $value['num'] * $value['price'];
                } else {
                    return jsonFail('该商品库存不足,商品名：' . $value['name']);
                }
            }
            $now_time = date("H:i", time());
            $flag = false;
            $time_interval = explode(',',$storeInfo['time_interval']);
            //判断时间点
            foreach ($time_interval as $v) {
                $time = explode('-', $v);
                if ($now_time >= $time[0] && $now_time <= $time[1]) {//在营业时间
                    $flag = true;
                    break;
                }
            }
            if ($flag==true) {//在营业时间
                if (round($total_back, 2) != $total) return jsonFail('总价不相同', $total_back);
                $order = create_order_no();//生成订单号
                $total_backa = bcadd($total_back, $delivery_price, 2);
                $total_backc = bcadd($total_backa, $floor_price, 2);//服务费+配送费+商品费用+餐盒费
                $total_backb = bcadd($total_backc, $lunchbox_price, 2);//服务费+配送费+商品费用+餐盒费
                $dormitory = json_decode($schoolInfo['dormitory-' . $userAddressInfo['dormitory_id']], true);//楼栋信息
//                $floor_name = $dormitory['floor-' . $userAddressInfo['floor_id']];//楼层名称
                $company = $schoolInfo['company'];//配置公司百分比
                $operate = $storeInfo['proportion'];//运营方百分比
                if ($schoolInfo['type'] == 1 && $is_raised == 1) {//判断是否有配送员
                    $sends = Db::table('eb_user')->where('delivery_storied', $userAddressInfo['dormitory_id'])->where('is_system_order_taking', 1)->where('delivery_floor', $userAddressInfo['floor_id'])->field('id')->find();
                    if (empty($sends)) return jsonFail('该楼层暂无配送员，请选择自提方式');
                }
                $company_price = round($total_backb * ($company / 100), 2);//公司提成
                if ($storeInfo['is_special'] == 1) {//1:抽成商家 2：保障商家
                    $store_price = round($total_back * ((100 - $operate) / 100), 2);//商家
                } else {
                    $store_price = $total_back;
                }
                $dec_goodsid = array_column($cart_data, 'goods_id');
                $dec_goodsnum = array_column($cart_data, 'num');
                $result = array_merge($dec_goodsid, $dec_goodsnum);
                $descGoodsLua = file_get_contents(app()->getAppPath() . 'lua/desc_goods.lua');//加载
                Db::startTrans();
                $orderId = Db::table('eb_order')->insertGetId([
                    'code' => substr(microtime(), -6),//生成提货码
                    'pay_type' => $pay_type,//支付类型
                    'order_no' => $order,
                    'manag_id' => $dormitory['manag_id'],
                    'total_price' => $total_backb,//总价
                    'delivery_price' => $delivery_price,//服务费
                    'lunchbox_price'=>$lunchbox_price,//餐盒费
                    'floor_price' => $floor_price,//楼层配送费，跑腿
                    'goods_price' => $total_back,//商品费用
                    'company_price' => $company_price,//公司提成
                    'operate_id' => $schoolInfo['operate_id'],//运营方id
                    'store_price' => $store_price + $store_price_tmp,//商家方提成
                    'box_price'=>$schoolInfo['box_price'],//装箱员费用
                    'dor_manager_price'=>$schoolInfo['dor_manager_price'],//装箱员费用
                    'operate_price' => $total_backb - ($company_price + $store_price +$store_price_tmp + $floor_price+$schoolInfo['box_price']+$schoolInfo['dor_manager_price']),//运营方提成
                    'user_id' => $user_id,
                    'store_id' => $store_id,
                    'store_name' => $storeInfo['shop_name'],
                    'school_id' => $userInfo['school_id'],
                    'dormitory_id' => $userAddressInfo['dormitory_id'],
                    'floor_id' => $userAddressInfo['floor_id'],
                    'remark' => $remark,
                    'is_raised' => $is_raised,//1:送货上楼 2：下楼自取
                    'address_id' => $address_id,
                    'create_time' => time(),
                ]);
                if ($orderId != 0) {
                    foreach ($cart_data as $key => $value) {
                        if (!array_key_exists('type', $value)) {
                            Db::rollback();
                            return jsonFail('为了更好的服务广大学生，系统进行了版本升级,增加了套餐组合可选的配置，请清空购物车，右上角刷新后再下单哦~', '', 201);
                        }
                        $res = Db::table('eb_order_detail')->insertGetId([
                            'store_id'=>$store_id,
                            'order_id' => $orderId,
                            'goods_id' => $value['goods_id'],
                            'goods_name' => $value['name'],
                            'goods_num' => $value['num'],
                            'goods_price' => $value['price'],
                            'meat_text' => $value['meat_text'],
                            'veg_text' => $value['veg_text'],
                            'type' => $value['type'],
                            'create_time' => time(),
                        ]);
                        if (empty($res)) {
                            Db::rollback();
                            return jsonFail('生成订单失败！');
                        }
                        if ($value['type'] == 2) {//为套餐时需要减少库存
                            $meat_text = explode(',', $value['meat_text']);
                            $veg_text = explode(',', $value['veg_text']);
                            foreach ($meat_text as $v) {//减少荤菜库存
                                $red = Db::execute("update eb_goods_conf  set `stock`=`stock`-{$value['num']} where store_id={$store_id } and stock>=1 and `name` ='{$v}'");
                                if ($red == false) return jsonFail('荤菜减少库存失败', $red);
                            }
                            foreach ($veg_text as $v) {//减少素菜库存
                                $red = Db::execute("update eb_goods_conf  set `stock`=`stock`-{$value['num']} where store_id={$store_id } and stock>=1 and `name` ='{$v}'");
                                if ($red == false) return jsonFail('素菜减少库存失败', $red);
                            }
                        }
                        if ($value['stock'] >= $value['num']) {
                            $red = Db::execute("update eb_goods  set stock=stock- " . $value['num'] . " where id=" . $value['goods_id'] . " and stock>=" . $value['num']);
                            if ($red == false) return jsonFail('减少库存失败', $red);
                        } else {
                            Db::rollback();
                            return jsonFail('库存不足'.$value['name'].',需求量：'.$value['stock']);
                        }
                    }
                    $decgoodsRtn = Cache::store('redis')->handler()->eval($descGoodsLua, $result, count($goodsIds));//商品ID，数量
                    if ($decgoodsRtn === -400) {
                        Db::rollback();
                        return jsonFail('商品库存不足');
                    } else if (array_sum($decgoodsRtn) == 0) {
//                            $addRtn = Cache::store('redis')->handler()->lPush('dxsd-order-list', json_encode($orderdata));//生成订单缓存
//                            if ($addRtn !=0) {//订单写入缓存成功
                        $delRtn = Cache::store('redis')->handler()->Del('dxsd-cart-' . $user_id . '-' . $store_id);
                        if ($delRtn === 1) {
                            try {
                                $carts = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->field('id')->find();
                                $res = Db::table('eb_cart_detail')->where('cart_id', $carts['id'])->delete();
                                $res = Db::table('eb_cart')->where('id', $carts['id'])->delete();
//                                file_put_contents('/tmp/time.txt', microtime(true) - $start . PHP_EOL, FILE_APPEND);
                                Db::commit();
                                return jsonSuccess('订单生成成功', ['order_no' => $order]);
                            } catch (\Exception $e) {
                                Db::rollback();
                                return jsonFail($e->getMessage());
                            }
                        } else {
                            Db::rollback();
                            return jsonFail('购物车删除失败', $delRtn);
                        }
                    } else {
                        Db::rollback();
                        return jsonFail('订单扣除缓存失败');
                    }
                }
//                        $goods = Db::table("eb_goods");
//                        foreach ($cart_data as $key => $value) {
//                            $res = Db::table('eb_order_detail')->insertGetId([
//                                'order_id' => $orderId,
//                                'goods_id' => $value['goods_id'],
//                                'goods_name' => $value['name'],
//                                'goods_num' => $value['num'],
//                                'goods_price' => $value['price'],
//                                'create_time' => time(),
//                            ]);
//                            if (empty($res)) return jsonFail('生成订单失败！');
//                            $stock = $goods->where('id', $value['goods_id'])->field('stock')->find();
//                            if ($stock > $value['num']) {
//                                $red = Db::execute("update eb_goods  set stock=stock- " . $value['num'] . " where id=" . $value['goods_id'] . " and stock>=" . $value['num']);
//                                if ($red == false) return jsonFail('减少库存失败', $red);
//                            } else {
//                                Db::rollback();
//                                return jsonFail('库存不足');
//                            }
//                        $decgoodsRtn = Cache::store('redis')->handler()->eval($descGoodsLua, $result, count($goodsIds));//商品ID，数量
//                        if ($decgoodsRtn === -400) {
//                            return jsonFail('商品库存不足');
//                        } else if (array_sum($decgoodsRtn) == 0) {
////                            $addRtn = Cache::store('redis')->handler()->lPush('dxsd-order-list', json_encode($orderdata));//生成订单缓存
////                            if ($addRtn !=0) {//订单写入缓存成功
//                                $delRtn = Cache::store('redis')->handler()->Del('dxsd-cart-' . $user_id . '-' . $store_id);
//                                if ($delRtn === 1) {
//                                    try {
//                                        $carts = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->field('id')->find();
//                                        $res = Db::table('eb_cart_detail')->where('cart_id', $carts['id'])->delete();
//                                        $res = Db::table('eb_cart')->where('id', $carts['id'])->delete();
//                                        return jsonSuccess('订单生成成功', ['order_no' => $order]);
//                                    } catch (\Exception $e) {
//                                        return jsonFail('购物车删除失败');
//                                    }
//                                } else {
//                                    return jsonFail('购物车删除失败');
//                                }
//                            }else{
//                                return jsonFail('订单写入缓存失败',$addRtn);
//                            }
//                        } else {
//                            file_put_contents('/tmp/order-error.txt', json_encode($error_data), FILE_APPEND);
//                            $res = json_decode(Send_msg('tx', 15583730896, 'template1', 200, 3), true);
//                            return jsonFail('系统错误，请联系管理员！');
//                        }
            } else {
                return jsonFail('不在配送时间段，请更改时间段下单哦');
            }
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /** 获取所有订单
     * @param Request $request
     */
    public function order_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $page = $this->request->param('page', 1);//
        $limit = $this->request->param('limit', 20);//用户ID
        if (empty($user_id)) return jsonFail('缺少用户ID');
        $data = Db::table('eb_order')->where('user_id', $user_id)->order('create_time', 'desc')->page($page, $limit)->select()->toArray();
        foreach ($data as $key => &$value) {
//            $value['school_name'] = Db::table('eb_school')->where('id', $value['school_id'])->field('name')->find();
//            $value['dormitory_name'] = Db::table('eb_dormitory')->where('id', $value['dormitory_id'])->field('name')->find();
            $value['order_detail'] = Db::table('eb_order_detail')->where('order_id', $value['id'])->select()->toArray();
            $value['store'] = Db::table('eb_store')->where('id', $value['store_id'])->field('id,shop_name,logo,bank_phone,is_refues')->find();
            foreach ($value['order_detail'] as $key1 => &$value1) {
                $value1['goods'] = Db::table('eb_goods')->where('id', $value1['goods_id'])->select()->toArray();
            }
            if (!is_null($value['send_id'])) {//有配送员
                $value['send'] = Db::table('eb_user')->where('id', $value['send_id'])->field('name,phone')->find();
            }
        }
        return jsonSuccess('获取成功', $data);
    }

    /**用户评论订单、评价
     * @param Request $request
     * @return \think\response\Json
     */
    public function comment(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $order_no = $this->request->param('order_no');//订单编号
        $store_comment = $this->request->param('store_comment', '');//商家评论
        $store_score = $this->request->param('store_score');//商家评分
        $send_comment = $this->request->param('send_comment', '');//送货员评论
        $send_score = $this->request->param('send_score');//商家评分
        if (empty($send_score) || empty($store_score)) return jsonFail('缺少参数');
        if ($store_score > 10) return jsonFail('满分10，请检查评分哟！');
        if ($send_score > 10) return jsonFail('满分10，请检查评分哟！');
        $order = Db::table('eb_order')->where('order_no', $order_no)->find();
        if (empty($order)) return jsonFail('暂无订单');
        try {
            Db::startTrans();
            $res = Db::table('eb_order')->where('order_no', $order_no)->update(['comment' => $store_comment, 'status' => 6]);
            $mark_id = Db::table('eb_mark')->insertGetId(['order_no' => $order_no, 'type' => 1, 'score' => $store_score, 'sid' => $order['store_id']]);
            if ($mark_id != 0) {
                $avg = Db::table('eb_mark')->where('type', 1)->where('sid', $order['store_id'])->avg('score');
                Db::table('eb_store')->where('id', $order['store_id'])->update(['score' => $avg]);
            } else {
                return jsonFail('评价失败');
            }
            $mark_ids = Db::table('eb_mark')->insertGetId(['order_no' => $order_no, 'type' => 2, 'score' => $send_score, 'sid' => $order['send_id'], 'comment' => $send_comment]);
            if ($mark_ids) {
                Db::commit();
                return jsonSuccess('评价成功');
            }
            Db::rollback();
            return jsonFail('评价失败');
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail('系统错误~');
        }
    }

    /**商户获取自己订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function storeGetList(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $input['page'] = $request->post('page'); // 当前页
        $input['limit'] = $request->post('limit'); // 每页显示数量
        //验证参数
        $validate = Validate::rule([
            'page' => ValidateRule::isRequire(null, '缺少参数'),
            'limit' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return OrderModel::storeGetList($input, $request->param('token'));
    }

    /**根据状态商户获取自己订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function statusGetList(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $input['page'] = $request->post('page'); // 当前页
        $input['limit'] = $request->post('limit'); // 每页显示数量
        $input['status'] = $request->post('status'); // 状态
        //验证参数
        $validate = Validate::rule([
            'page' => ValidateRule::isRequire(null, '缺少参数'),
            'limit' => ValidateRule::isRequire(null, '缺少参数'),
            'status' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return OrderModel::statusGetList($input, $request->param('token'));
    }

    /**用户申请退款
     * @param Request $request
     * @return \think\response\Json
     */
    public function Apply_refund(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $order_no = $request->post('order_no'); //订单号
        $back_reason = $request->post('back_reason'); //退款原因
        if (empty($order_no) || empty($back_reason)) return jsonFail('缺少参数');
        try {
            $send = new \API_PHP_DEMO();
            $store = Db::table('eb_order')->alias('a')->leftJoin('eb_store b', 'a.store_id = b.id')->where('a.order_no', $order_no)->field('b.sn');
            $res = Db::table('eb_order')->where('order_no', $order_no)->update(['status' => -1, 'back_reason' => $back_reason]);
            $data = combination_cancel(14, 6, 3, 6);
            $code = $send->printMsg($store['sn'], $data);
            if ($res != 0) return jsonSuccess('申请成功');
            return jsonFail('申请失败');
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /** 查询当前订单信息
     * @param Request $request
     */
    public function order_info(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $order_no = $request->post('order_no'); //订单号
        $data = Db::table('eb_order')->alias('a')
            ->leftJoin('eb_user b', 'a.send_id = b.id')
            ->leftJoin('eb_store c', 'a.store_id = c.id')
            ->leftJoin('eb_user_address d', 'a.address_id = d.id')
            ->leftJoin('eb_dormitory e', 'd.dormitory_id = e.id')
            ->leftJoin('eb_floor f', 'd.floor_id = f.id')
            ->where('a.order_no', $order_no)
            ->field('a.*,b.name as send_name,b.phone as send_phone,c.bank_phone,c.shop_name,d.name as consignee_name,d.phone as consignee_phone,d.address as consignee_address,e.name as dormitory_name,f.name as floor_name')->find();
        $data['goods'] = Db::table('eb_order_detail')->alias('a')
            ->where('a.order_id', $data['id'])
            ->field('a.type,a.veg_text,a.meat_text,a.goods_num,a.goods_num * a.goods_price as amount,a.goods_name')->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /** 根据条件所有订单
     * @param Request $request
     */
    public function find_order_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $page = $this->request->param('page', 1);//
        $limit = $this->request->param('limit', 20);//用户ID
        $text = $this->request->param('text');//搜索内容
        if (empty($user_id)) return jsonFail('缺少用户ID');
        if (empty($text)) return jsonSuccess('获取成功', []);
        $order = Db::table('eb_order')->alias('a')
            ->join('eb_order_detail b', 'a.id = b.order_id')
            ->join('eb_store c', 'a.store_id = c.id')
            ->join('eb_user d', 'a.send_id = d.id')
            ->whereRaw(" `a`.`user_id` = {$user_id} AND ( `a`.`store_name` LIKE '%{$text}%'   OR  `b`.`goods_name` LIKE '%{$text}%' )")
            ->page($page, $limit)
            ->field('a.pay_type,a.send_id,d.phone as send_phone,a.status,a.create_time,c.id,a.order_no,b.type,b.veg_text,b.meat_text,b.goods_num * b.goods_price as amount,c.shop_name,c.logo,c.bank_phone')
            ->select()
            ->toArray();

        foreach ($order as $key => &$value) {
            $order[$key]['store']['id'] = $value['id'];
            $order[$key]['store']['shop_name'] = $value['shop_name'];
            $order[$key]['store']['logo'] = $value['logo'];
            if (array_key_exists($value['send_id'], $order)) {
                $order[$key]['send']['phone'] = $value['send_phone'];
                unset($value['send_phone']);
            }
            unset($value['id']);
            unset($value['shop_name']);
            unset($value['logo']);
            unset($value['send_id']);
        }
        return jsonSuccess('获取成功', $order);
    }

    /** 查询订单商品库存
     * @param Request $request
     */
    public function find_order_stock(Request $request)
    {
        $order_no = $request->param('order_no');//订单编号
        if (empty($order_no)) return jsonFail('缺少参数');
        $order = Db::table('eb_order')->where('order_no', $order_no)->field('id')->find();
        $cart_list = Db::table('eb_order_detail')->where('order_id', $order['id'])->field('goods_id,num')->select()->toArray();
        foreach ($cart_list as $key => $value) {
            $stock = Db::table("eb_goods")->where('id', $value['goods_id'])->field('stock')->find();
            if ($stock < $value['num']) {
                return jsonFail('该商品库存不足');
            }
        }
    }

}
